from pathlib import Path


ROOT_DIR = Path(__file__).resolve().parents[1]
SRC_DIR = Path.joinpath(ROOT_DIR, "logs")
README = Path.joinpath(ROOT_DIR, "README.md")


def read_md_title(file):
    """read the first title of the .md file"""
    with open(file, "r", encoding="utf8") as f:
        for line in f:
            if line.startswith("#"):
                return line.strip("#").strip()


def get_md_files(src=SRC_DIR):
    """iterate SRC_DIR to find all the .md files in the directory"""
    md_files = [file for file in src.iterdir() if file.suffix == ".md"]

    # sort the .md files by the last modified time
    md_files.sort(key=lambda file: file.stat().st_mtime, reverse=True)
    return md_files


def render_md_link(file):
    """render a hyperlink to the .md file in the README.md file
    [title](file)

    - title: the first title of the .md file
    - file: the relative path to the .md file
    """
    title = read_md_title(file)
    file_relative_path = file.relative_to(ROOT_DIR).as_posix()
    return f"- [{title}](<{file_relative_path}>)"


def refresh_readme(readme=README, links: list = None):
    """refresh the content of the README.md file with the .md files in the SRC_DIR"""
    with open(readme, "w", encoding="utf8") as f:
        f.write("\n".join(links))


def main():
    print("auto refresh begin...")
    md_files = get_md_files()
    links = [render_md_link(file) for file in md_files]
    refresh_readme(links=links)
    print("auto refresh done")


if __name__ == "__main__":
    main()
